"""HTTP(S) endpoints."""
from cki_lib import misc
from cki_lib.logger import get_logger
import flask
import sentry_sdk
from sentry_sdk.integrations.flask import FlaskIntegration

from . import slack
from .alertmanager import craft_notification

app = flask.Flask(__name__)

misc.sentry_init(sentry_sdk, integrations=[FlaskIntegration()], environment=app.debug)

LOGGER = get_logger(__name__)


@app.route('/', methods=['GET'])
def index():
    """Return a nearly empty page."""
    return flask.Response(response='OK', status='200')


@app.route('/message', methods=['POST'])
def message_receiver():
    """Route a generic message."""
    data = flask.request.get_json()
    message = data['message']
    slack.send_message(message)
    return flask.Response(response='OK', status='200')


@app.route('/alertmanager', methods=['POST'])
def alertmanager_receiver():
    """Route an alertmanager message."""
    data = flask.request.get_json()
    alertmanager_url = data['externalURL']
    LOGGER.info('alertmanager %s', data)

    if message := craft_notification(data['alerts'], alertmanager_url, 'resolved'):
        slack.send_message(message)

    if message := craft_notification(data['alerts'], alertmanager_url, 'firing'):
        slack.send_message(message)

    return flask.Response(response='OK', status='200')
